package 文件io;

import java.io.*;
import java.util.zip.*;
/**
 测试aide 解压缩可以但是压缩后文件有的损坏
*/
public class 文件压缩与解压
{
	public static void main(String[] args){
		//compress("/storage/emulated/0/360.zip",new File("/storage/emulated/0/360"));
		decompression("storage/emulated/0/360.zip","storage/emulated/0/360/");
	}
	
	private static void compress(String zipFileName,File targetFile){
		System.out.println("正在压缩...");
		
		try
		{   ////创建zip输出流
			ZipOutputStream out=new ZipOutputStream(new FileOutputStream(zipFileName));
			BufferedOutputStream bos=new BufferedOutputStream(out);
			zip(out,targetFile,targetFile.getName(),bos);
			bos.close();
			out.close();
		}
		catch (FileNotFoundException e)
		{}
		catch(IOException e){}
		System.out.println("压缩成功");
	}
	//zip压缩操作
	private static void zip(ZipOutputStream zout, File targetFile, String name, BufferedOutputStream bos) throws IOException
	{
		if(targetFile.isDirectory()){//判断如果是目录先获取目录下文件列表
			File[] files=targetFile.listFiles();
			if(files.length==0){//如果是空目录直接处理
				zout.putNextEntry(new ZipEntry(name+"/"));
			}
			for(File file:files){//遍历目录，利用递归深入所有文件夹
				zip(zout,file,name+"/"+file.getName(),bos);
			}
		}else{//如果是文件进行压缩操作
			zout.putNextEntry(new ZipEntry(name));
			//读文件的套路，读完之后直接bos写入
			InputStream in= new FileInputStream(targetFile);
			BufferedInputStream bis=new BufferedInputStream(in);
			byte[] bytes=new byte[1024];
			int len=-1;
			while((len=bis.read(bytes))!=-1){
				bos.write(bytes,0,len);
			}
			bis.close();
		}	
	}
	private static void decompression(String targetFileName,String parent){
		try
		{
			ZipInputStream zIn=new ZipInputStream(new FileInputStream(targetFileName));
			ZipEntry entry=null;
			File file=null;
			while((entry=zIn.getNextEntry())!=null&&!entry.isDirectory()){
				file=new File(parent,entry.getName());
				if(!file.exists()){
					new File(file.getParent()).mkdirs();
				}
				OutputStream out=new FileOutputStream(file);
				BufferedOutputStream bos=new BufferedOutputStream(out);
				byte[] bytes=new byte[1024];
				int len=-1;
				while((len=zIn.read(bytes))!=-1){
					bos.write(bytes,0,len);
				}
				bos.close();
				System.out.println(file.getName()+" 解压成功");
			}
		}
		catch (FileNotFoundException e)
		{}
		catch(IOException e){}

	}
}
